package com.tyros.web.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.tyros.common.kit.web.lock.DatabaseLock;
import com.tyros.common.kit.web.lock.Lock;
import com.tyros.common.kit.web.mybatis.DefaultMetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author zhangshuaiyin
 * @date 2022/7/2 19:47
 */
@Slf4j
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class MybatisAutoConfiguration {
    /**
     * 新版分页插件，注意选择数据库
     *
     * @return MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        log.info("Mybatis Plus 分页插件配置完成...");
        return interceptor;
    }

    /**
     * MyBatisPlus自定义字段自动填充处理类
     * 实体类中使用 @TableField 注解配置填充字段和填充策略
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new DefaultMetaObjectHandler();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = "lock.db.enabled", havingValue = "true")
    public Lock databaseLock(DataSource dataSource, @Value("${lock.db.sql:}") String lockSql) {
        return new DatabaseLock(dataSource, lockSql);
    }
}
